package com.py.credit.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.common.ServiceException;
import com.py.credit.constant.SubjectTypConstant;
import com.py.credit.dao.ZwcxSearchDao;
import com.py.credit.entity.ColumnResult;
import com.py.credit.entity.ContentStyle;
import com.py.credit.entity.DataResult;
import com.py.credit.entity.TableResult;
import com.py.credit.service.ContentStyleService;
import com.py.credit.service.ZwcxSearchService;
import com.py.credit.utils.NumberUtils;
import com.py.credit.utils.SQLBuilder;
import com.py.credit.utils.elasticsearch.EsConstants;
import com.py.credit.utils.elasticsearch.EsPage;
import com.py.credit.utils.elasticsearch.EsQueryEntity;
import com.py.credit.utils.elasticsearch.EsQueryUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.rest.support.RestServiceResult;

@Service
public class ZwcxSearchServiceImpl implements ZwcxSearchService{

	@Autowired
	private ZwcxSearchDao zwcxSearchDao;
	@Autowired
	private ContentStyleService contentStyleService;
	
	@Override
	public List<Map<String, Object>> getByConditionForPage(String kId, List<String> showColumns,
			String[] additionalColumns, String condition, Page page) {
		if (CollectionUtils.isEmpty(showColumns)) {

			throw new ServiceException("至少选择一列");

		}
		List<String> conditions = SQLBuilder.createConditionSql(condition);

		List<Map<String, Object>> tables = zwcxSearchDao.selectByConditionForPage(kId, showColumns, additionalColumns,
				page, conditions);

		return tables;
	}

	@Override
	public List<Map<String, Object>> getSharingSearchHistoryList(long userId, String kId) {
		return zwcxSearchDao.selectSharingSearchHistoryList(userId, kId);
	}

	@Override
	public Map<String, Object> getUniqueList(Map<String, Object> map) {
		return zwcxSearchDao.selectUniqueList(map);
	}

	@Override
	public List<Map<String, String>> getSubjectLsitForPage(String kId, String input, Page page) {
		String whereSql = null;

		List<Map<String, String>> list = new ArrayList<>();

		if (SubjectTypConstant.SUJECT_TYPE_FR.equals(kId)) {

			whereSql = "A000001 LIKE '" + input + "%' OR A000002 = '" + input + "'";

		} else if (SubjectTypConstant.SUJECT_TYPE_ZWJG.equals(kId)) {

			whereSql = "C000001 LIKE '" + input + "%' OR C000002 = '" + input + "'";

		} else if (SubjectTypConstant.SUJECT_TYPE_GWY.equals(kId)) {

			whereSql = "B000001 LIKE '" + input + "%' OR B000002 = '" + input + "'";
		}

		if (whereSql != null) {

			list = zwcxSearchDao.selectUniqueByKeyForPage(kId, whereSql, page);

			if (!CollectionUtils.isEmpty(list) && SubjectTypConstant.SUJECT_TYPE_GWY.equals(kId)) {

				for (Map<String, String> map : list) {

					String idEncrypt = NumberUtils.idEncrypt(map.get("B000002"));

					map.put("B000002", idEncrypt);

				}
			}

		}

		return list;
	}

	@Override
	public List<Map<String, String>> getKeyWordsByEs(String kId, String input, EsPage esPage) {
			List<Map<String, String>> selectUniqueAKeyWords = null;
			List<EsQueryEntity> where = new ArrayList<>(1);
			String[] s = null;
			if("100000".equals(kId)) {
				s = new String[] { "A000001", "A000002" };
			}
			else if ("100001".equals(kId)) {
				s = new String[] { "B000001", "B000002" };
			} else {
				s = new String[] { "C000001", "C000002" };
			}
			EsQueryEntity e = new EsQueryEntity(EsConstants.SHOULD, s, input);
			where.add(e);
			// EsPage page = new EsPage();
			RestServiceResult<List<Map<String, Object>>> restServiceResult = EsQueryUtil.getList(esPage,
					EsQueryUtil.whereBuilder(where), null, "doc", EsConstants.INDEX_PREFIX + kId);
			if (RestServiceResult.CODE_SUCCESS == restServiceResult.getCode()) {
				String result = JSON.toJSONString(restServiceResult.getData());
				selectUniqueAKeyWords = JSONObject.parseObject(result, new TypeReference<List<Map<String, String>>>() {
				});
				// 身份证脱敏
				if ("100001".equals(kId) && !CollectionUtils.isEmpty(selectUniqueAKeyWords)) {
					for (Map<String, String> map : selectUniqueAKeyWords) {
						String idEncrypt = NumberUtils.idEncrypt(map.get("B000002"));
						map.put("B000002", idEncrypt);
					}
				}
			}
			return selectUniqueAKeyWords != null ? selectUniqueAKeyWords : new ArrayList<>();
	}

	
	@Override
	public List<Map<String, String>> getKeyWords(String kId, String input) {

		List<Map<String, String>> selectUniqueAKeyWords = null;
		if ("100001".equals(kId)) {

			selectUniqueAKeyWords = zwcxSearchDao.selectUniqueBKeyWords(kId, input);

			// 身份证脱敏

			if (!CollectionUtils.isEmpty(selectUniqueAKeyWords)) {

				for (Map<String, String> map : selectUniqueAKeyWords) {

					String idEncrypt = NumberUtils.idEncrypt(map.get("B000002"));

					map.put("B000002", idEncrypt);

				}
			}

		} else {

			selectUniqueAKeyWords = zwcxSearchDao.selectUniqueCKeyWords(kId, input);

		}

		return selectUniqueAKeyWords != null ? selectUniqueAKeyWords : new ArrayList<Map<String, String>>();
	}
	
	
	@Override
	public void addHistory(String tybm, String kId, long userId) {
		int updateHistory = zwcxSearchDao.updateHistory(tybm, kId, userId);

		if (updateHistory == 0) {

			zwcxSearchDao.addHistory(tybm, kId, userId);
		}
	}

	@Override
	public List<TableResult> assembleTableComponent(List<TableResult> list) {

		if (!CollectionUtils.isEmpty(list)) {

			Set<String> hitIds = new HashSet<String>();

			// 获取配置样式
			List<ContentStyle> contentStyles = contentStyleService.getByType("ZWCX");

			for (TableResult table : list) {

				boolean hit = false;

				StringBuffer sb = new StringBuffer();

				String tableId = table.getTableId();

				String tableShowType = table.getShowType();

				List<DataResult> datas = table.getData();

				// id 匹配的用配置样式 ，否者固定样式
				for (ContentStyle contentStyle : contentStyles) {

					String styleTableId = contentStyle.getTableId();

					if (tableId.equalsIgnoreCase(styleTableId)) {

						hit = true;

						hitIds.add(tableId);

						String tableStyle = contentStyle.getTableStyle();

						if (StringUtils.isNotBlank(tableStyle)) {

							// 有样式单表

							if ("S".equals(tableShowType)) {
								// 有数据
								if (!CollectionUtils.isEmpty(datas)) {

									DataResult dataResult = datas.get(0);

									String addTime = dataResult.getAddTime() == null ? ""
											: dataResult.getAddTime().substring(0, 10);

									List<ColumnResult> columns = dataResult.getColumns();

									org.jsoup.nodes.Document parse = Jsoup.parse(tableStyle);

								

									for (ColumnResult column : columns) {

										Element element = parse.getElementById(column.getMetricCode());

										if (element != null) {

											element.text(column.getValue() == null ? "" : column.getValue());

										}

									}

									sb.append(parse.getElementsByTag("table").toString());

								} else {
									// 无数据直接返回样式
									sb.append("<div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");
								}

							} else {

								// 有样式多表
								// 有数据
								if (!CollectionUtils.isEmpty(datas)) {

									org.jsoup.nodes.Document parse = Jsoup.parse(tableStyle);

									for (DataResult dataResult : datas) {

										List<ColumnResult> columns = dataResult.getColumns();

										String addTime = dataResult.getAddTime() == null ? ""
												: dataResult.getAddTime().substring(0, 10);

										for (ColumnResult column : columns) {

											String value = column.getValue() == null ? "" : column.getValue();

											Element element = parse.getElementById(column.getMetricCode());

											if (element != null) {

												element.text(value);

											}

										}

									

										sb.append(parse.getElementsByTag("table").toString());

									}

								} else {

									// 无数据直接返回样式

									sb.append("<div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");

								}

							}

						} else {

							// 默认样式单表

							if ("S".equals(tableShowType)) {

								if (!CollectionUtils.isEmpty(datas)) {

									// 获取最新的一条记录
									DataResult dataResult = datas.get(0);

									List<ColumnResult> columns = dataResult.getColumns();

									String addTime = dataResult.getAddTime() == null ? ""
											: dataResult.getAddTime().substring(0, 10);
									sb.append("<table><tbody>");

									for (ColumnResult columnResult : columns) {

										String metricName = columnResult.getMetricName();

										String value = columnResult.getValue() == null ? "" : columnResult.getValue();

										sb.append("<tr><td>" + metricName + "</td><td>" + value + "</td></tr>");

									}

									sb.append("</tbody></table>");

								} else {
									// 空数据默认样式返回表头

									sb.append("<div></div><div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");

									// List<Column> columns =
									// table.getColumns();
									//
									// for (Column column : columns) {
									//
									// String metricName =
									// column.getMetricName();
									//
									// sb.append("<tr><td>" + metricName +
									// "</td><td></td></tr>");
									//
									// }

									// sb.append("</tbody></table>");

								}

							} else {

								// 默认样式多表

								if (!CollectionUtils.isEmpty(datas)) {

									for (DataResult dataResult : datas) {

										String addTime = dataResult.getAddTime() == null ? ""
												: dataResult.getAddTime().substring(0, 10);

										List<ColumnResult> columns = dataResult.getColumns();

										sb.append("<table><tbody>");

										for (ColumnResult column : columns) {

											String metricName = column.getMetricName();

											String value = column.getValue() == null ? "" : column.getValue();

											sb.append("<tr><td>" + metricName + "</td><td>" + value + "</td></tr>");

										}

										sb.append("</tbody></table>");

									}

								} else {

									sb.append("<div></div><div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");

									// // 空数据默认样式返回表头
									// List<Column> columns =
									// table.getColumns();
									//
									// for (Column column : columns) {
									//
									// String metricName =
									// column.getMetricName();
									//
									// sb.append("<tr><td>" + metricName +
									// "</td><td></td></tr>");
									//
									// }

									// sb.append("</tbody></table>");

								}

							}

						}

						break;
					}

				}

				if (!hit) {

					// 默认样式单表

					if ("S".equals(tableShowType)) {

						if (!CollectionUtils.isEmpty(datas)) {
							sb.append("<table><tbody>");
							// 获取最新的一条记录
							DataResult dataResult = datas.get(0);

							List<ColumnResult> columns = dataResult.getColumns();
							String addTime = dataResult.getAddTime() == null ? ""
									: dataResult.getAddTime().substring(0, 10);
					
							sb.append("<table><tbody>");

							for (ColumnResult columnResult : columns) {

								String metricName = columnResult.getMetricName();

								String value = columnResult.getValue() == null ? "" : columnResult.getValue();

								sb.append("<tr><td>" + metricName + "</td><td>" + value + "</td></tr>");

							}

							sb.append("</tbody></table>");

						} else {

							sb.append("<div></div><div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");
							// 空数据默认样式返回表头
							// List<Column> columns = table.getColumns();
							//
							// for (Column column : columns) {
							//
							// String metricName = column.getMetricName();
							//
							// sb.append("<tr><td>" + metricName +
							// "</td><td></td></tr>");
							//
							// }

							// sb.append("</tbody></table>");

						}

					} else {

						// 默认样式多表

						if (!CollectionUtils.isEmpty(datas)) {

							for (DataResult dataResult : datas) {

								String addTime = dataResult.getAddTime() == null ? ""
										: dataResult.getAddTime().substring(0, 10);

								List<ColumnResult> columns = dataResult.getColumns();

					
								sb.append("<table><tbody>");

								for (ColumnResult column : columns) {

									String metricName = column.getMetricName();

									String value = column.getValue() == null ? "" : column.getValue();

									sb.append("<tr><td>" + metricName + "</td><td>" + value + "</td></tr>");

								}

								sb.append("</tbody></table>");

							}
						} else {

							sb.append("<div></div><div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");
							// 空数据默认样式返回表头
							// List<Column> columns = table.getColumns();
							//
							// for (Column column : columns) {
							//
							// String metricName = column.getMetricName();
							//
							// sb.append("<tr><td>" + metricName +
							// "</td><td></td></tr>");
							//
							// }

							// sb.append("</tbody></table>");

						}

					}
				}
				table.setTableComponent(sb.toString());
				table.setColumns(null);
				table.setData(null);
			}

		}

		return list;
	}

}
